<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-form-item label="维度名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-row :gutter="8">
              <a-input
                v-decorator="['dimensionName', validatorRules.dimensionName]"
                placeholder="请输入维度名称"
              ></a-input>
            </a-row>
          </a-form-item>
           <a-form-item label="数据源名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
              @change="dataSourceChange"
              placeholder="请选择数据源"
              :options="dataSourceOptions"
              allow-clear
              v-decorator="['code']"
            >
            </a-select>
            </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="字典表">
            <a-row :gutter="8">
              <a-col :span="18" name="dictTable">
                <a-select
                  placeholder="请选择字典表"
                  v-show="showtable"
                  :disabled="true"
                  v-decorator="['dictTable']"
                  allow-clear
                  @change="onChange"
                  :getPopupContainer="trigger => trigger.parentNode"
                >
                <a-select-option :value="item.tableName" :key="item.index" v-for="item in tableArr">
                      {{ item.tableName }}
                  </a-select-option>
                </a-select>
                <a-select
                  placeholder="请选择字典表"
                  v-show="!showtable"
                  :disabled="false"
                  v-decorator="['dictTable']"
                  allow-clear
                  @change="onChange"
                  :getPopupContainer="trigger => trigger.parentNode"
                >
                 <a-select-option :value="item.tableName" :key="item.index" v-for="item in tableArr">
                      {{ item.tableName }}
                  </a-select-option>
                </a-select>
              </a-col>
              <a-col :span="6">
                <a-button
                  class="atn-testbtn"
                  type="primary"
                  size="small"
                  style="width: 100%"
                  @click="checkdict"
                >查看字典表</a-button>
              </a-col>
            </a-row>
          </a-form-item>
          <a-col :span="24">
            <a-form-item label="字典编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-show="showtable" :disabled="true" v-decorator="['dictCode']" placeholder="请输入字典编号"></a-input>
              <a-input v-show="!showtable" :disabled="false" v-decorator="['dictCode']" placeholder="请输入字典编号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="字典值" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-show="showtable" :disabled="true" v-decorator="['dictValue']" placeholder="请输入字典值"></a-input>
              <a-input v-show="!showtable" :disabled="false" v-decorator="['dictValue']" placeholder="请输入字典值"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="默认值" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['defaultValue']" placeholder="请输入默认值"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['remark']" placeholder="请输入备注"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="状态">
              <a-radio-group
                name="radioGroup"
                v-decorator="['status', {
                  initialValue: 1,
                  rules: [{required: true}]
                }]"
              >
                <a-radio :value="1">启用</a-radio>
                <a-radio :value="0">停用</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
    <!-- 查看字典表弹窗 -->
    <view-dictionary-table ref="ViewDictionarlist" @change="childChange"></view-dictionary-table>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import ViewDictionaryTable from './ViewDictionaryTable'

export default {
  name: 'ScSituationIndexInfoForm',
  components: {
    ViewDictionaryTable
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {},
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      form: this.$form.createForm(this),
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {
        dimensionName: { rules: [{ required: true, message: '请输入维度名称!' }] }
      },
      identity: '1',
      url: {
        add: '/dimension/scSituationDimensionType/add',
        edit: '/dimension/scSituationDimensionType/edit'
        // queryById: '/dimension/scSituationDimensionType/queryById'
      },
      tabIndex: '1',
      showtable: false,
      dataSourceOptions: [],
      tableArr: []
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  watch: {
    // $store.state.project.dict  ===  获取state里面的值
    // 赋值给字典code
    '$store.state.project.dict': {
      // （val==》新数据，oldval===》旧数据）
      handler(val, oldVal) {
        if (this.tabIndex == 1) {
          this.form.setFieldsValue({ dictCode: val })
        }
      }
    },
    '$store.state.project.category': {
      handler(val, oldVal) {
        if (this.tabIndex == 2) {
          this.form.setFieldsValue({ dictCode: val })
        }
      }
    }
    // // 点击字典配置赋值给字典值
    // '$store.state.project.deploy': {
    //   // （val==》新数据，oldval===》旧数据）
    //   handler(val, oldVal) {
    //     if (this.tabIndex == 1) {
    //       this.form.setFieldsValue({ dictValue: val })
    //     }
    //   }
    // }
  },
  created() {
    // 如果是流程中表单，则需要加载流程表单data
    // this.showFlowData()
    this.getDataSourceList()
  },
  methods: {
    // 点击字典table并清空关联的字典code和字典表
    onChange(e) {
      this.$nextTick(() => {
        if (!this.form.getFieldValue('dictTable')) {
          this.form.setFieldsValue({ dictCode: '' })
          this.form.setFieldsValue({ dictValue: '' })
        }
      })
    },
    // 数据源下拉框数据
    getDataSourceList() {
      this.$get('/sys/dataSource/list?pageNo=1&pageSize=1000').then(res => {
        this.dataSourceOptions = res.result.records
        this.dataSourceOptions.map(item => {
          item.value = item.code
          item.title = item.name
        })
      })
    },
    // 切换数据源
    dataSourceChange(value, options) {
      this.$get(`/index/config/listTables?code=${value}`).then(res => {
        this.tableArr = res.result
      })
    },
    add() {
      this.edit({})
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(
            this.model,
            'dimensionName',
            'dictCode',
            'status',
            'dictTable',
            'dictValue',
            'sysOrgCode',
            'createBy',
            'createTime',
            'remark'
          )
        )
      })
      // 双击输入框解除禁用
      const vm = this
      document.getElementsByName('dictTable')[0].ondblclick = function() {
        vm.showtable = false
      }
    },
    // 渲染流程表单数据
    // showFlowData() {
    //   if (this.formBpm === true) {
    //     const params = { id: this.formData.dataId }
    //     getAction(this.url.queryById, params).then((res) => {
    //       if (res.success) {
    //         this.edit(res.result)
    //       }
    //     })
    //   }
    // },
    // 查看字典表点击事件
    checkdict() {
      this.showtable = true
      this.$refs.ViewDictionarlist.edit()
      this.form.setFieldsValue({ dictTable: 'sys_dict' })
      this.form.setFieldsValue({ dictValue: 'dict_name' })
    },
    // tab(字典table)
    childChange(index) {
      // 自动输入时禁用
      this.showtable = true
      // 在这里进行判断
      this.tabIndex = index
      if (index == '1') {
        this.form.setFieldsValue({ dictTable: 'sys_dict' })
        this.form.setFieldsValue({ dictValue: 'dict_name' })
        this.form.setFieldsValue({ dictType: '1' })
      } else {
        this.form.setFieldsValue({ dictTable: 'sys_category' })
        this.form.setFieldsValue({ dictValue: 'name' })
        this.form.setFieldsValue({ dictType: '2' })
      }
      // tab切换时关联的字段进行清空
      this.form.setFieldsValue({ dictCode: '' })
      // this.form.setFieldsValue({ dictValue: '' })
    },
    handleCheck() {
      this.showtable = false
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          const formData = Object.assign(this.model, values)
          console.log('表单提交数据', formData)
          httpAction(httpurl, formData, method)
            .then(res => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    popupCallback(row) {
      this.form.setFieldsValue(
        pick(
          row,
          'dimensionName',
          'dictCode',
          'dictTable',
          'dictValue',
          'sysOrgCode',
          'createBy',
          'createTime',
          'remark'
        )
      )
    }
  }
}
</script>
<style lang="less" scoped>
.atn-testbtn {
  color: #2f77f2 !important;
  background: #ffffff !important;
  box-shadow: 0px 1px 3px 0px rgba(4, 0, 0, 0.08) !important;
  border: 1px solid #2f77f2 !important;
  border-radius: 2px !important;
  padding: 0 10px !important;
  height: 34px !important;
  margin: 0 8px 8px 0;
}
</style>
